package cn.edu.zhku.aspect;

import cn.edu.zhku.aspect.annotation.CheckGroupTaskExist;
import cn.edu.zhku.constant.ResponseCode;
import cn.edu.zhku.dto.BaseDto;
import cn.edu.zhku.service.GroupService;
import cn.edu.zhku.util.PojoUtil;
import cn.edu.zhku.util.ResultUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(4)
public class CheckGroupTaskExistAspect extends BaseDtoAspect {

    @Autowired
    private GroupService groupService;

    @Pointcut("@annotation(cn.edu.zhku.aspect.annotation.CheckGroupTaskExist)")
    public void pointcut() {}

    @Around("baseDtoPointcut() && pointcut()")
    public Object checkGroupTaskExist(ProceedingJoinPoint joinPoint) throws Throwable {
        CheckGroupTaskExist checkGroupTaskExist = ((MethodSignature)joinPoint.getSignature())
                                                    .getMethod().getAnnotation(CheckGroupTaskExist.class);
        String value = checkGroupTaskExist.value();
        boolean batch = checkGroupTaskExist.batch();
        BaseDto baseDto = (BaseDto) joinPoint.getArgs()[0];
        if (batch) {
            if (PojoUtil.group.notExistGroupTasks(this.groupService, baseDto.getGroupId(), baseDto.getTaskIds()))
                return ResultUtil.getResult(ResponseCode.conflict, value);
        } else {
            if (PojoUtil.group.notExistGroupTasks(this.groupService, baseDto.getGroupId(), PojoUtil.pojo.convert2TaskIds(baseDto.getTaskId())))
                return ResultUtil.getResult(ResponseCode.conflict, value);
        }
        return joinPoint.proceed();
    }

}
